import datetime
import os
import random
import subprocess
import time
import traceback

import numpy
import pandas as pd
import requests
from loguru import logger
from playwright.sync_api import sync_playwright
import single_login


class ChenFeng:
    def __init__(self, playwright, host, command):
        self.playwright = playwright
        self.host = host
        self.command = command
        self.login_func = single_login.Login(playwright, host, command)
        self.download_path = os.path.join(os.getcwd(), "download", "product")
        if not os.path.exists(self.download_path):
            os.mkdir(self.download_path)

    def download_file(self):
        yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
        month = yesterday.strftime("%Y%m")
        for i in range(20):
            logger.info('【{}】秒【20】秒'.format(i + 1))
            time.sleep(1)
            if self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("更多")') is not None and \
                    self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("更多")').is_visible():
                logger.info("页面加载完成...")
                break
        # 悬停在右上角菜单
        self.login_func.page.query_selector('//*[@id="header"]/div/div/div[3]/div/div[5]').hover()
        time.sleep(0.5)
        shop_name_list = []
        # 获取所有经销商
        li_list = self.login_func.page.query_selector_all(
            'div.header-right-item:has(span.current-supplier-name) >> li.ascp-frame-menu-item')[1:]
        for li in li_list:
            shop_name_list.append(li.text_content())
        # 检查是否有数据按钮
        has_data_button = False
        # 循环查询每个经销商
        for index, shop_name in enumerate(shop_name_list):
            for i in range(20):
                logger.info('【{}】秒【20】秒'.format(i + 1))
                time.sleep(1)
                if self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("更多")') is not None and \
                        self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("更多")').is_visible():
                    break
            # 点击更多
            self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("更多")').click()
            time.sleep(2)
            if self.login_func.page.query_selector('ul.nav-more >> li:has-text("数据")') is not None and \
                    self.login_func.page.query_selector('ul.nav-more >> li:has-text("数据")').is_visible():
                self.login_func.page.query_selector('ul.nav-more >> li:has-text("数据")').click()
                self.wait(self.login_func.page)
                has_data_button = True
            else:
                if self.login_func.page.query_selector('ul.nav-more >> li:has-text("天机")') is not None and \
                    self.login_func.page.query_selector('ul.nav-more >> li:has-text("天机")').is_visible():
                    self.login_func.page.query_selector('ul.nav-more >> li:has-text("天机")').click()
                    self.wait(self.login_func.page)
                    has_data_button = True
            if not has_data_button:
                logger.error("网站没有【数据】按钮...")
                logger.info("尝试点击【天机】按钮...")
                if self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("天机")') is not None and \
                        self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("天机")').is_visible():
                    self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("天机")').click()
                    self.wait(self.login_func.page)
                    has_data_button = True
            if not has_data_button:
                logger.error("网站没有【天机】按钮...")
                break
            # 点击商品分析
            logger.info('点击【商品分析】...')
            self.login_func.page.query_selector('a:has-text("商品分析")').click()
            self.wait(self.login_func.page)
            logger.info('等待10秒页面加载完成...')
            for i in range(5):
                logger.info('【{}】秒【5】秒'.format(i + 1))
                time.sleep(1)
                logger.info("检查是否弹窗遮住了按钮...")
                if self.login_func.page.query_selector('//div[contains(@class, "aes-survey-page--close")]') is not None and \
                        self.login_func.page.query_selector('//div[contains(@class, "aes-survey-page--close")]').is_visible():
                    logger.info("弹窗遮住了按钮...")
                    self.login_func.page.query_selector('//div[contains(@class, "aes-survey-page--close")]').click()
            frame = None
            for k in range(10):
                # 先调用一下，否则会找不到
                self.login_func.page.query_selector('//*[@id="header"]/div/div/div[3]/div/div[5]')
                frame = self.login_func.page.frame(url='https://web.txcs.tmall.com/pages/chaoshi/ai_tj_item_v2*')
                if frame is not None:
                    break
                time.sleep(1)
            # 点击明细查询
            if frame is None:
                logger.info('点击明细查询异常')
            self.wait(frame)
            time.sleep(2)
            logger.info('点击【明细查询】...')
            frame.query_selector('li:has-text("明细查询")').click()
            self.wait(frame)
            time.sleep(1)
            # 点击【明细查询】【区域】下拉框
            # logger.info('点击【明细查询】【区域】下拉框...')
            # frame.query_selector('div.comp-block:has(div.comp-toolbar:has-text("明细查询")) >> div.select-filter:has(div.common-filter-label:has-text("区域")) >> input').click()
            # time.sleep(2)
            # self.login_func.page.keyboard.press("Arrow Down")
            # time.sleep(1)
            # 选择整体
            # with self.login_func.page.expect_response('https://ascp-dc.tmall.com/api/v1/queryData/api-ascp-dc-ai_tj_item_v2/olap?*') as res:
            #     self.login_func.page.keyboard.press("Enter")
            # response = res.value
            # self.wait(frame)
            # time.sleep(2)
            # 点击品仓明细
            logger.info('点击【品仓明细】...')
            with self.login_func.page.expect_response(
                    '*queryData/api-ascp-dc-ai_tj_item_v2/olap*') as res:
                frame.query_selector('div.next-tabs-tab-inner:has-text("品仓明细")').click()
            response = res.value
            response_obj = response.json()
            logger.info("品仓明细：{}", response_obj)
            self.wait(frame)
            time.sleep(2)
            has_data = False
            text_list = frame.query_selector_all('div.comp-toolbar-title')
            for text in text_list:
                if '品仓明细查询' in text.text_content() and '(' in text.text_content():
                    has_data = True
                    break
            if not has_data:
                logger.info(f'经销商【{shop_name}】暂无数据')
            else:
                total = frame.query_selector_all('span.comp-toolbar-title-total')[-1].text_content()
                logger.info(f'经销商【{shop_name}】共{total}条数据')
                for i in range(3):
                    try:
                        logger.info("尝试把元素滚动到窗口范围内...")
                        frame.query_selector('div.next-tabs-tab-inner:has-text("品仓明细")').click()
                        time.sleep(1)
                        # 下载报表
                        frame.query_selector(
                            'div.comp-block:has(div.comp-toolbar:has-text("明细查询")) >> div[data-tip="下载"]:visible').click()
                        break
                    except:
                        logger.info("没有找到下载按钮，往下滚动...")
                        self.login_func.page.keyboard.press("PageDown")
                        time.sleep(1)
                time.sleep(5)
                for i in range(60):
                    if self.login_func.page.query_selector(
                            'div.notification-file-container >> ul >> li >> a:has-text("下载")') is not None and self.login_func.page.query_selector(
                            'div.notification-file-container >> ul >> li >> a:has-text("下载")').is_visible():
                        break
                    time.sleep(1)
                with self.login_func.page.expect_download() as download_info:
                    self.login_func.page.query_selector('div.notification-file-container >> ul >> li >> a:has-text("下载")').click()
                download_obj = download_info.value
                file_path = os.path.join(self.download_path, f'{shop_name}-商品信息.xlsx')
                # 删除旧文件
                if os.path.exists(file_path):
                    os.remove(file_path)
                download_obj.save_as(file_path)
                # 等待文件下载完成
                for i in range(60):
                    if os.path.exists(file_path):
                        self.upload_file(shop_name, file_path)
                        break
                    time.sleep(1)
                # 关闭消息弹窗
                self.login_func.page.query_selector('div.header-right-item:has(div#notification-center-mask)').click()
                time.sleep(1)
            # 如果是最后一个，跳出循环
            if index == len(shop_name_list) - 1:
                break
            time.sleep(2)
            # 悬停在右上角菜单
            self.login_func.page.query_selector('span.current-supplier-name').hover()
            time.sleep(1)
            self.login_func.page.query_selector(f'li.ascp-frame-menu-item:has-text("{shop_name_list[index + 1]}")').click()
            self.wait(self.login_func.page)
            time.sleep(5)
            # 关闭弹窗
            for i in range(5):
                try:
                    if len(self.login_func.page.query_selector_all('a.ascp-frame-dialog-close:visible')) > 0:
                        for dialog in self.login_func.page.query_selector_all('a.ascp-frame-dialog-close:visible'):
                            try:
                                dialog.click(timeout=3000)
                            except:
                                pass
                    time.sleep(1)
                except:
                    pass
            time.sleep(5)
            self.login_func.page.wait_for_selector('ul.nav-menu-list >> li:has-text("更多")')
            time.sleep(1)

    # 处理excel表格
    def handle_excel(self, file_list):
        for file in os.listdir(self.download_path):
            df = pd.read_excel(os.path.join(self.download_path, file),
                               usecols=['品牌', '商品ID', '货品ID', '良品可售库存件数', '28天日均销售件数', '支付金额', '支付商品件数', '支付用户数',
                                        '退款成功金额', '退款成功商品件数'])
            pass

    def run(self):
        self.login_func.login()
        self.download_file()

    def upload_file(self, carrier, file_path):
        try:
            url = self.host + "/goods/sysGoodsImport?carrier=" + carrier
            logger.info("正在上传文件到服务器：" + url)
            files = [
                ('file', (open(file_path, 'rb')))
            ]
            response = requests.request("POST", url, files=files)
            print(response.text)
        except:
            traceback.print_exc()

    def wait(self, page, seconds=1):
        page.wait_for_load_state(state="domcontentloaded")
        time.sleep(seconds)

    def close(self):
        try:
            if self.login_func.page:
                self.login_func.page.close()
        except:
            pass
        try:
            if self.login_func.browser:
                self.login_func.browser.close()
        except:
            pass
        try:
            if self.login_func.context:
                self.login_func.context.close()
        except:
            pass


def main(host, command):
    for i in range(6):
        try:
            with sync_playwright() as playwright:
                chen_feng = ChenFeng(playwright, host, command)
                chen_feng.run()
                chen_feng.close()
            return True
        except:
            logger.info(traceback.format_exc())
    return False
